#include "app_common.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "cJSON/cJSON.h"
#include "log/log.h"

//参数：char数组，数组大小
//返回值：json字符串
char * app_message_charsToJson(char *char_arry,int len){
    //1.获取前三元素，分别为连接类型，设备ID长度，消息长度
    int connect_type=char_arry[0];
    int id_len=char_arry[1];
    int msg_len=char_arry[2];
    //2.获取设备ID
    char device_id[id_len];
    memcpy(device_id,char_arry+3,id_len);
    //3.获取消息内容
    char msg[msg_len];
    memcpy(msg,char_arry+3+id_len,msg_len);
    //4.将id与msg转为16进制char数组（方便管理）
    char *id_hex=app_common_charToHex(device_id,id_len);
    char *msg_hex=app_common_charToHex(msg,msg_len);
    //5.转为json字符串（连接类型、设备ID、消息体）
    cJSON *root = cJSON_CreateObject();
    cJSON_AddNumberToObject(root, "conn_type", connect_type);
    cJSON_AddStringToObject(root, "id", id_hex);
    cJSON_AddStringToObject(root, "msg", msg_hex);
    char *json = cJSON_PrintUnformatted(root);
    cJSON_Delete(root);
    free(id_hex);
    free(msg_hex);
    return json;
}

//参数：json字符串，char数组长度的指针
//返回值：char数组
int app_message_JsonTochars(char *json,char *char_arry,int buf_len){
    //1.解析json
    cJSON *root = cJSON_Parse(json);
    int connect_type = cJSON_GetObjectItem(root, "conn_type")->valueint;
    char *device_id = cJSON_GetObjectItem(root, "id")->valuestring;
    char *msg = cJSON_GetObjectItem(root, "msg")->valuestring;
    //2.获取设备ID长度，消息长度
    int id_len = -1;
    int msg_len = -1;
    //3.将设备ID，消息体转为char数组
    char *id_char = app_common_hexToChar(device_id,&id_len);
    char *msg_char = app_common_hexToChar(msg,&msg_len);
    //判断缓存数组是否装不下
    int total_len = 3+id_len+msg_len;
    if(total_len>buf_len){
        log_error("buf_len is too small");
        return -1;
    }
    //4.将前三元素与id_char，msg_char合并
    char_arry[0] = connect_type;
    char_arry[1] = id_len;
    char_arry[2] = msg_len;
    memcpy(char_arry+3,id_char,id_len);
    memcpy(char_arry+3+id_len,msg_char,msg_len);
    //5.释放内存
    cJSON_Delete(root);
    free(id_char);
    free(msg_char);
    return total_len;
}

